package com.banksoft.admin.controller;

import com.banksoft.admin.dao.AdvertDao;
import com.banksoft.admin.entity.Advert;
import com.banksoft.admin.service.BaseService;
import com.banksoft.common.BaseController;
import com.banksoft.common.PageInfo;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/5.
 */
@Controller
@RequestMapping("/advert")
public class AdvertController extends BaseController {
    @Autowired
    BaseService baseService;

    @RequestMapping("/list")
    public String list(){
        return "advert/advert_list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public Object listData(String title,PageInfo pageInfo){

        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isNotNull(title))
            map.put("title",title);

        pageInfo.setParams(map);

        pageInfo = this.page(AdvertDao.class,pageInfo);

        return this.getPageResult(pageInfo);
    }


    @RequestMapping("/beforeEdit")
    public String beforeEdit(String id,Model model){
        if(StringUtil.isNotNull(id)){
            Advert advert = this.baseService.findById(AdvertDao.class,id);
            model.addAttribute("data",advert);
        }
        return "advert/advert_edit";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Object save(Advert advert,HttpServletRequest request){
        try {
            if (StringUtil.isNotNull(advert.getId())) {//编辑
                this.baseService.update(AdvertDao.class, advert);
                this.saveLog("编辑广告" + advert.getTitle(), request);
            } else {//新增
                advert.setId(UUIDFactory.random());
                this.baseService.insert(AdvertDao.class, advert);
                this.saveLog("新增广告：" + advert.getTitle(), request);
            }
            return this.FmtResult(true,"保存成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,"保存失败:"+e.getMessage(),null);
        }

    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String id,HttpServletRequest request){
        try{
            Advert advert = this.baseService.findById(AdvertDao.class,id);
            this.baseService.delete(AdvertDao.class,new String[]{id});

            this.saveLog("删除广告："+advert.getTitle(),request);
            return this.FmtResult(true,"操作成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,"操作失败"+e.getMessage(),null);
        }
    }

}
